package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.activity.FestivalActivity;
import com.ekuaitu.kuaitu.activity.GuideActivity;
import com.ekuaitu.kuaitu.activity.MainActivity;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.FestivalBean;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.NetUtils;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.utils.VerControlUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SplashActivity extends BaseActivity {

    @BindView(R.id.imageView_splash)
    ImageView imageViewSplash;
    private Context mContext = this;
    private boolean isInPerMission = false;
    private static final int PERMISSION_REQUESTCODE = 1;
    private NetworkInfoReceiver networkInfoReceiver;

    @Override
    public int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    public void initView() {

    /*    //账号测试,使用uid,toekn,免登录
        SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue(SharedPreferencesKey.USER_ID, "218857");
        SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue(SharedPreferencesKey.USER_TOKEN, "qubkwrt0wQ9fF2dN");
        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.USER_PHONE_NUM, "18500405669");
*/
        //设置启动界面全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!isInPerMission) {
            Animation animation = new AlphaAnimation(1.0f, 1.0f);
            animation.setDuration(1000);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                //启动界面结束后
                @Override
                public void onAnimationEnd(Animation animation) {
                    getLocationPermission();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
            imageViewSplash.startAnimation(animation);
        }
    }

    //获取动态权限
    private void getLocationPermission() {
        isInPerMission = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUESTCODE);
            } else {
                isNetAvailable();
            }
        } else {
            isNetAvailable();
        }

    }

    //处理权限的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUESTCODE:
                isInPerMission = false;  //向用户申请权限结束
                boolean isPermissionOk = true;

                for (int i = 0; i < permissions.length; i++) {
                    if (permissions[i].equals(Manifest.permission.ACCESS_COARSE_LOCATION) && grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        isPermissionOk = false;
                    }

                    if (permissions[i].equals(Manifest.permission.CAMERA) && grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        isPermissionOk = false;
                    }
                }

                if (isPermissionOk) {  //只要这三个权限允许了，就可以继续
                    isNetAvailable();
                } else {  //上面的三个权限有一个拒绝了，引导用户到设置开启权限
                    //向用户申请权限中
                    isInPerMission = true;
                    new AlertDialog.Builder(mContext).setTitle("小兔提示").setMessage("您拒绝了某些权限，部分功能将无法使用，请您到设置中开启权限。")
                            .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    isInPerMission = false;
                                    startAppSettings(mContext);
                                }
                            }).setCancelable(false).show();
                }
                break;

            default:
                break;
        }

    }


    //启动当前应用设置页面
    private static void startAppSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    private AlertDialog alertDialog;

    //检查网络连接状态
    private void isNetAvailable() {
        if (!NetUtils.isNetworkAvailable(mContext)) {
            //没有网络，注册网络改变监听
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            networkInfoReceiver = new NetworkInfoReceiver();
            registerReceiver(networkInfoReceiver, filter);
            if (alertDialog == null) {
                alertDialog = new AlertDialog.Builder(mContext).setTitle(getString(R.string.dialogTitle)).setMessage(getString(R.string.badNetwork))
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                AppManager.getAppManager().AppExit(mContext);
                            }
                        }).setCancelable(false).show();
            }
        } else {
            int oldVersionCode = SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.OLD_VERSION_CODE);
            int curVersionCode = new VerControlUtils(mContext).getVersionCode();
            if (oldVersionCode == 0 || oldVersionCode != curVersionCode) {
                startActivity(new Intent(mContext, GuideActivity.class));
                finish();
            } else {
                startActivity(new Intent(mContext, MainActivity.class));
                finish();
                // festivalOpen();
            }
        }
    }

    private void festivalOpen() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL_PHP).festivalOpen(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<FestivalBean>() {
                    @Override
                    public void onResponse(Call<FestivalBean> call, final Response<FestivalBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Date date = new Date();
                            if (date.getTime() >= response.body().getStart() && date.getTime() <= response.body().getEnd() && response.body().getStauts() == 1) {
                                startActivity(new Intent(mContext, FestivalActivity.class));
                            } else {
                                startActivity(new Intent(mContext, MainActivity.class));
                            }
                            finish();
                        } else {
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<FestivalBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //网络改变 广播接收
    private class NetworkInfoReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                if (NetUtils.isNetworkAvailable(context)) {
                    int oldVersionCode = SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.OLD_VERSION_CODE);
                    int curVersionCode = new VerControlUtils(mContext).getVersionCode();
                    if (oldVersionCode == 0 || oldVersionCode != curVersionCode) {
                        startActivity(new Intent(context, GuideActivity.class));
                        finish();
                    } else {
                        startActivity(new Intent(mContext, MainActivity.class));
                        finish();
                        //festivalOpen();
                    }
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (networkInfoReceiver != null) {
            unregisterReceiver(networkInfoReceiver);
        }
    }

}
